import $ajax from '../../utils/request'
import common from '../../utils/common'
// import match from './match-route'

const user = {
    state: {
        user: '', // 用于保存用户信息
        userRole: 0, // 用户角色 0 普通用户 1 机构管理员 2 数据局管理员 3 实施人员
        hadUserInfo: false
    },

    mutations: {
        SET_USER: (state, user) => {
            // if (user.authTree && user.authTree.children[0]) {
            //     let sideMenus = match.routeMatch(user.authTree.children.filter(e => {
            //             if (e.type === 2 && e.code.indexOf('top-menu') < 0) return e
            //         }), match.sideRoute),
            //         topMenus = match.routeMatch(user.authTree.children.filter(e => {
            //             if (e.type === 2 && e.code.indexOf('top-menu') >= 0) return e
            //         }), match.topRoute)
            //     user.sideMenus = sideMenus
            //     user.topMenus = topMenus
            // }
            state.user = user
        },
        SET_USERROLE: (state, userRole) => {
            state.userRole = userRole
        },
        SET_HADUSERINFO: (state, whether) => {
            state.hadUserInfo = whether
        }
    },

    actions: {
        setUser({commit}, user) {
            commit('SET_USER', user)
        },
        setUserRole({commit}, user) {
            let userRole = 0, approve = false, implcom = false, superman = false
            if (user.roleDtos && user.roleDtos[0]) {
                user.roleDtos.forEach(item => {
                    if (item.code === '#RESDIR_IMPLEMENTATION' && !implcom) implcom = true
                    if (item.code === '#RESDIR_DATAMANA_MANAGER' && !superman) superman = true
                    if (item.code === '#RESDIR_DEPT_MANAGER' && !approve) approve = true
                })
            }
            if (superman) { // 数据局管理员
                userRole = 2
            } else if (approve) { // 部门管理员
                userRole = 1
            } else if (implcom) { // 实施人员
                userRole = 3
            }
            commit('SET_USERROLE', userRole)
        },
        loginBySession({commit, state, dispatch}) {
            // 请求登录信息，成功后赋值给user对象
            return new Promise((resolve, reject) => {
                let token = common.getUrlParam('token_enc'),
                    params = token ? {token_enc: token} : {}
                $ajax.get('/deptAdmin/userInfo', params).then(res => {
                    if (res.data) {
                        dispatch('setUser', res.data)
                        dispatch('setUserRole', res.data)
                    }
                    commit('SET_HADUSERINFO', true)
                    resolve(res.data)
                }).catch(err => {
                    commit('SET_HADUSERINFO', true)
                    reject(err)
                })
            })
        }
    }
}

export default user
